import { compose } from 'redux'

import createWs from '../../network/ws'

import { dispatchOpen, dispatchMessage, dispatchClose } from '../actions/wsDispatchMessageAction'

export const WS_CONNECT = 'ws_connect'
export const WS_DISCONNECT = 'ws_disconnect'
export const WS_SEND_DATA = 'ws_send_data'

function createWsMiddleware () {
  let ws
  const buildWs = (dispatch) => {
    ws = createWs()
    ws.onOpen(compose(dispatch, dispatchOpen))
    ws.onMessage(compose(dispatch, dispatchMessage))
    ws.onClose(compose(dispatch, dispatchClose))
  }
  return ({ dispatch, getState }) => next => action => {
    switch (action.type) {
      case WS_CONNECT: {
        buildWs(dispatch)
        break
      }
      case WS_DISCONNECT: {
        if (ws) {
          ws.disconnect()
        }
        break
      }
      case WS_SEND_DATA: {
        if (ws) {
          ws.sendData(action.data)
        }
        break
      }
      default: return next(action)
    }
  }
}

const wsMiddleware = createWsMiddleware()

export default wsMiddleware
